﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using BrettM.SimpleDemo.WebApp.Models;

namespace BrettM.SimpleDemo.WebApp.Store.XmlStore
{
    public class XmlStore
        : ISimpleDemoStore
    {
        private static DataSet _store;


        private string XmlFilename
        {
            get { return HttpContext.Current.Server.MapPath("~/App_Data/DemoStore.xml"); }
        }

        private string SchemaFilename
        {
            get { return HttpContext.Current.Server.MapPath("~/App_Data/DemoStore.xsd"); }
        }

        private DataSet Store()
        {
            if (_store == null)
            {
                _store = new DataSet("DemoStore");
                _store.ReadXmlSchema(SchemaFilename);
                _store.ReadXml(XmlFilename);
            }

            return _store;
        }

        private void WriteStore()
        {
            if (_store == null) return;
            _store.WriteXml(XmlFilename);
        }


        public CustomerList GetCustomers()
        {
            var customers = Store().Tables["Customer"].AsEnumerable();
            var result =
                (from c in customers
                 select new Customer()
                            {
                                Code = c.Field<string>("code"),
                                FirstName = c.Field<string>("FirstName"),
                                LastName = c.Field<string>("LastName"),
                                Telephone = c.Field<string>("Telephone"),
                            }).ToArray();

            return new CustomerList(result);
        }


        public Customer GetCustomer(string code)
        {
            var customers = Store().Tables["Customer"].AsEnumerable();
            var result =
                (from c in customers
                 where c.Field<string>("code") == code
                 select new Customer()
                 {
                     Code = c.Field<string>("code"),
                     FirstName = c.Field<string>("FirstName"),
                     LastName = c.Field<string>("LastName"),
                     Telephone = c.Field<string>("Telephone"),
                 }).SingleOrDefault();

            return result;
        }

        public void UpdateCustomer(Customer newCustomer)
        {
            var customers = Store().Tables["Customer"];

            var foundRows = Store().Tables["Customer"].Select(string.Format("code='{0}'", newCustomer.Code));
            if (foundRows.Count() != 1) return;

        }


        private string GetNextCustomerCode(string firstName, string lastName)
        {
            var prefix = firstName.Substring(0, 1) + lastName.Substring(0, 1);
            var customers = Store().Tables["Customer"].AsEnumerable();
            var result =
                (from c in customers
                 where c.Field<string>("code").StartsWith(prefix, true, CultureInfo.InvariantCulture)
                 select c.Field<string>("code"))
                 .ToList();

            int id = 1;
            foreach (var item in result)
            {
                var itemKey = int.Parse(item.Substring(2));
                if (itemKey >= id) id = itemKey + 1;
            }

            return string.Format("{0}{1:000}", prefix, id);

        }

        public void AddCustomer(NewCustomer customer)
        {
            var customers = Store().Tables["Customer"];

            var newRow = customers.NewRow();
            newRow.SetField("code", GetNextCustomerCode(customer.FirstName, customer.LastName));
            newRow.SetField("FirstName", customer.FirstName);
            newRow.SetField("LastName", customer.LastName);
            newRow.SetField("Telephone", customer.Telephone);

            customers.Rows.Add(newRow);

            WriteStore();
        }

        public bool DeleteCustomer(string code)
        {
            var customers = Store().Tables["Customer"];

            var foundRows = Store().Tables["Customer"].Select(string.Format("code='{0}'", code));
            if (foundRows.Count() != 1) return false;

            customers.Rows.Remove(foundRows[0]);
            WriteStore();
            return true;

        }
    }
}